package com.bluefox.hospital.convertor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bluefox.common.web.dto.AbstractConvertor;
import com.bluefox.hospital.dto.ImageDTO;
import com.bluefox.hospital.model.Image;
import com.bluefox.hospital.service.ImageService;
import lombok.NonNull;

import java.time.ZoneId;
import java.util.Date;

/**
 * ImageConvertor
 */
@Component
public class ImageConvertor extends AbstractConvertor<Image, ImageDTO> {

    @Autowired
    private ImageService imageService;

    @Override
    public Image toModel(@NonNull final ImageDTO dto) {
        if (dto.isNew()) {//新增
            return constructModel(dto);
        } else {//更新
            return updateModel(dto);
        }
    }

    @Override
    public ImageDTO toDTO(@NonNull final Image model, final boolean forListView) {
        final ImageDTO dto = new ImageDTO();
        dto.setId(model.getId());
        dto.setPhoto(model.getPhoto());
        dto.setName(model.getName());
        dto.setType(model.getType());
        dto.setCreatedDate(Date.from(model.getCreatedDate().get().atZone(ZoneId.systemDefault()).toInstant()));
        dto.setCreatedBy(model.getCreatedBy().get());
        dto.setAutoOrder(model.getAutoOrder());
        return dto;
    }

    // 构建新Model
    private Image constructModel(final ImageDTO dto) {
        Image model = new Image();
        model.setPhoto(dto.getPhoto());
        model.setName(dto.getName());
        model.setType(dto.getType());
        model.setAutoOrder(dto.getAutoOrder());
        return model;
    }

    // 更新Model
    private Image updateModel(final ImageDTO dto) {
        Image model = imageService.get(dto.getId());
        model.setPhoto(dto.getPhoto());
        model.setName(dto.getName());
        model.setAutoOrder(dto.getAutoOrder());

        return model;
    }
}
